package com.p.lib.widget.scroller;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Scroller;

/**
 * Created by Administrator on 2018/6/6 0006.
 */

public class ScrollLinearLayout extends LinearLayout {

    private boolean mFinished = false;

    private Scroller mScroller;

    /**
     * 滚动结束监听器
     */
    public interface OnScrollFinishedListener{
        public void onScrollFinished(ViewGroup scrollView);
    }


    private OnScrollFinishedListener onScrollFinishedListener;

    /**
     * 设置滚动监听器
     * @param onScrollFinishedListener
     */
    public void setOnScrollFinishedListener(OnScrollFinishedListener onScrollFinishedListener) {
        this.onScrollFinishedListener = onScrollFinishedListener;
    }

    /**
     * 移除滚动监听器
     */
    public void removeOnScrollFinishedListener() {
        this.onScrollFinishedListener = null;
    }

    public ScrollLinearLayout(Context context) {
        this(context, null);
    }

    public ScrollLinearLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScrollLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mScroller = new Scroller(context);
    }

    /**
     * 调用此方法滚动到目标位置
     * @param fx
     * @param fy
     * @param duration
     */
    public void smoothScrollTo(int fx, int fy, int duration){

        int dx = fx - getScrollX();
        int dy = fy - getScrollY();

        smoothScrollBy(dx, dy, duration);

    }

    /**
     * 调用此方法设置滚动的相对偏移
     * @param dx
     * @param dy
     * @param duration
     */
    public void smoothScrollBy(int dx, int dy, int duration){

        mFinished = false;
        //设置mScroller的滚动偏移量
        mScroller.startScroll(getScrollX(), getScrollY(), dx, dy, duration);
        //调用invalidate()才能保证computeScroll（）被调用， 否则不一定会刷新界面， 看不到滚动效果
        invalidate();

    }

    @Override
    public void computeScroll() {

        //先判断滚动是否完成
        if(mScroller.computeScrollOffset()){
            //这里调用 View 的 scrollTo（）完成实际滚动
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            //必须调用该方法， 否则不一定能看到滚动效果
            postInvalidate();

            if(mScroller.isFinished()){
                mFinished = true;
                if(onScrollFinishedListener != null){
                    onScrollFinishedListener.onScrollFinished(this);
                }
            }
        }

        super.computeScroll();
    }
}
